<template>
  <div class="rounded-xl shadow-lg border h-full">
    <!-- 第一阶段：文件上传 -->
    <div v-show="currentStep === 1" class=" rounded-xl p-16 !h-full">
      <el-upload ref="uploadRef" class="upload-demo" drag :auto-upload="false" :show-file-list="false"
        accept=".csv,.xlsx,.xls" :on-change="handleUploadChange" :limit="1">
        <div class="flex flex-col items-center gap-5">
          <div class="upload-icon">
            <img src="@/assets/icons/file.png" alt="">
          </div>
          <div class="mt-4">
            <p class="text-base text-gray-800 mb-2">将文件拖拽至此区域，或 <span class="text-[#2B6E50] font-bold">点击添加</span></p>
            <p class="text-sm text-gray-500 mb-0 mt-1">支持CSV、EXCEL格式，限制10MB以内；CSV只支持UTF-8编码格式</p>
          </div>
        </div>
      </el-upload>
    </div>

    <!-- 第二阶段：上传进度 -->
    <div v-show="currentStep === 2" class=" rounded-xl p-20 text-center">
      <div class="flex flex-col items-center gap-5">
        <div class="file-icon">
          <img src="@/assets/icons/file.png" alt="">
        </div>
        <div>
          <p class="text-base text-gray-800 mb-0">{{ fileName }}</p>
          <p class="text-sm text-gray-500 mb-0 mt-1">正在上传中...</p>
        </div>
      </div>
    </div>

    <!-- 第三阶段：数据展示 -->
    <div v-show="currentStep === 3"
      class="data-wrap bg-white rounded-xl p-6 flex flex-col justify-between h-full overflow-y-auto">
      <div>
        <div class="flex justify-between items-center pb-5 border-b border-gray-200 mb-6">
          <div class="flex items-center gap-3">
            <div class="w-10 h-10 bg-green-700 rounded flex items-center justify-center">
              <span class="text-white font-bold text-base">X</span>
            </div>
            <div>
              <p class="text-base font-medium text-gray-800 mb-0">{{ fileName }}</p>
              <p class="text-sm text-gray-500 mb-0">文件大小：{{ fileSize }}</p>
              <el-button type="primary" link @click="reupload">重新上传</el-button>
            </div>
          </div>

        </div>

        <div class="mb-8">
          <h3 class="text-base text-gray-800 mb-4">数据表展示 <span
              class="text-sm text-gray-500 font-normal">(可上下左右滑动)</span>
          </h3>
          <el-table :data="tableData" border style="width: calc(100vw - 74rem)" maxHeight="calc(100vh - 45rem)">
            <el-table-column align="center" prop="fenChang" label="分场" width="100" />
            <el-table-column align="center" prop="linBan" label="林班" width="80" />
            <el-table-column align="center" prop="xiaoBan" label="小班" width="100" />
            <el-table-column align="center" prop="shuZhong" label="树种" width="80" />
            <el-table-column align="center" prop="zaoLinFangShi" label="造林方式" width="90" />
            <el-table-column align="center" prop="mianJi" label="面积" width="80" />
            <el-table-column align="center" prop="linMuQuanShuLeiXing" label="林木权属类型" width="110" />
            <el-table-column align="center" prop="senLinLeiBie" label="森林类别" width="90" />
            <el-table-column align="center" prop="qiYuan" label="起源" width="80" />
            <el-table-column align="center" prop="poDu" label="坡度" width="80" />
            <el-table-column align="center" prop="liDiZhiLiang" label="立地质量" width="90" />
            <el-table-column align="center" prop="diMao" label="地貌" width="80" />
            <el-table-column align="center" prop="tuRangMuZhi" label="土壤母质" width="90" />
            <el-table-column align="center" prop="tuRangZhongLei" label="土壤种类" width="90" />
            <el-table-column align="center" prop="tuCengHouDu" label="土层厚度" width="90" />
          </el-table>
        </div>

        <h3 class="text-base text-gray-800 mb-4">数据表分析</h3>
        <div class="analyze-wrap">
          <div v-html="analyze"></div>
        </div>
      </div>

    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick, computed } from 'vue'
import * as echarts from 'echarts'
import { uploadFile } from '@/api/upload'
import { ElMessage } from 'element-plus'
import { useChatService } from '@/composables/useChatService';
import type { ChatMessage } from '@/types/chat';

const currentStep = ref(1)
const fileName = ref('')
const fileSize = ref('')
const uploadProgress = ref(0)
const uploadRef = ref()
const lineChart = ref<HTMLElement>()
const pieChart = ref<HTMLElement>()

const fileId = defineModel<string>('fileId')

const tableData = ref<any>([])

// 处理上传文件变化
const handleUploadChange = (file: any) => {
  if (file.raw) {
    processFile(file.raw)
  }
}

// 处理文件
const processFile = async (file: File) => {
  // 文件大小校验（10MB = 10 * 1024 * 1024 bytes）
  const maxSize = 10 * 1024 * 1024
  if (file.size > maxSize) {
    ElMessage.error('文件大小不能超过10MB')
    return
  }

  fileName.value = file.name
  fileSize.value = file.size > 1024 * 1024
    ? (file.size / (1024 * 1024)).toFixed(2) + 'MB'
    : (file.size / 1024).toFixed(2) + 'KB'

  currentStep.value = 2

  try {
    const data: any = await uploadFile(file)
    tableData.value = data.data

    currentStep.value = 3
    fileId.value = data.id
    getAnalyze(data.id)
    nextTick(() => {
      initCharts()
    })
  } catch (error) {
    ElMessage.error('文件上传失败，请重试')
    currentStep.value = 1
  }
}

// 重新上传
const reupload = () => {
  currentStep.value = 1
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }
}

// 初始化图表
const initCharts = () => {
  if (lineChart.value) {
    const lineChartInstance = echarts.init(lineChart.value)
    lineChartInstance.setOption({
      grid: { top: 20, right: 20, bottom: 40, left: 40 },
      xAxis: {
        type: 'category',
        data: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug'],
        axisLine: { show: false },
        axisTick: { show: false }
      },
      yAxis: {
        type: 'value',
        max: 100,
        axisLine: { show: false },
        axisTick: { show: false },
        splitLine: { lineStyle: { color: '#f0f0f0' } }
      },
      series: [{
        data: [20, 40, 35, 50, 80, 45, 30, 25],
        type: 'line',
        smooth: true,
        areaStyle: { color: 'rgba(33, 150, 243, 0.1)' },
        lineStyle: { color: '#2196F3', width: 2 },
        itemStyle: { color: '#2196F3' },
        symbol: 'circle',
        symbolSize: 6
      }]
    })
  }

  if (pieChart.value) {
    const pieChartInstance = echarts.init(pieChart.value)
    pieChartInstance.setOption({
      legend: {
        orient: 'vertical',
        right: 10,
        top: 'center',
        textStyle: { fontSize: 12 }
      },
      series: [{
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['40%', '50%'],
        data: [
          { value: 70, name: '70% Sent', itemStyle: { color: '#2196F3' } },
          { value: 45, name: '45% Read', itemStyle: { color: '#FFC107' } },
          { value: 30, name: '30% Unread', itemStyle: { color: '#E0E0E0' } }
        ],
        label: { show: false },
        emphasis: { scale: false }
      }]
    })
  }
}

const { sendToAI } = useChatService()
const analyze = ref('')
const getAnalyze = (fileId: string) => {
  sendToAI(
    '',
    'sjbfx',
    [],
    '',
    undefined,
    // 传递保存消息的回调函数
    async (aiMessage: ChatMessage) => {
      // await historyStore.saveMessage(aiMessage)
      // console.log(aiMessage)
      analyze.value = aiMessage.content
    },
    { fileId }
  ).catch()
}
</script>

<style scoped>
/* 自定义样式补充 */
.w-30 {
  width: 120px;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f6f8fa !important;
  color: #24292f;
  font-weight: 500;
}

:deep(.el-table td) {
  color: #24292f;
}

:deep(.el-upload-dragger) {
  border: none;
  border-radius: 12px !important;
  background: transparent !important;
  padding: 0 !important;
  width: 100% !important;
  height: auto !important;
}

:deep(.el-upload-dragger:hover) {
  border-color: #2196F3 !important;
  background: #fafbfc !important;
}
.data-wrap{
  height: calc(100vh - 230px);
}
.data-wrap::-webkit-scrollbar {
  display: none;
}
</style>
